﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ConnectionSelector.cs" company="">
//   
// </copyright>
// <summary>
//   Defines the ConnectionSelector type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace ComparisonTool.Forms.Connection
{
    using System;
    using System.Linq;
    using System.Windows.Forms;

    using ComparisonTool.Connection;

    using Microsoft.Xrm.Sdk.Client;

    /// <summary>
    /// The connection selector.
    /// </summary>
    public partial class ConnectionSelector : Form
    {
        /// <summary>
        /// The connection manager.
        /// </summary>
        private readonly ConnectionManager connectionManager;

        /// <summary>
        /// The had created new connection.
        /// </summary>
        private bool hadCreatedNewConnection;

        /// <summary>
        /// Initializes a new instance of the <see cref="ConnectionSelector"/> class.
        /// </summary>
        /// <param name="connections">
        /// The connections.
        /// </param>
        /// <param name="connectionManager">
        /// The c manager.
        /// </param>
        public ConnectionSelector(CrmConnections connections, ConnectionManager connectionManager)
        {
            this.InitializeComponent();
            this.connectionManager = connectionManager;
            connections.Connections.Sort();

            this.LoadImages();

            foreach (var detail in connections.Connections)
            {
                var groupName = string.Empty;

                switch (detail.AuthType)
                {
                    case AuthenticationProviderType.ActiveDirectory:
                        groupName = "OnPremise";
                        break;
                    case AuthenticationProviderType.OnlineFederation:
                        groupName = "CRM Online - Office 365";
                        break;
                    case AuthenticationProviderType.LiveId:
                        groupName = "CRM Online - CTP";
                        break;
                    case AuthenticationProviderType.Federation:
                        groupName = "Claims authentication - Internet Facing Deployment";
                        break;
                }

                var group = this.lvConnections.Groups.Cast<ListViewGroup>().FirstOrDefault(g => g.Name == groupName);
                if (group == null)
                {
                    group = new ListViewGroup(groupName, groupName);
                    this.lvConnections.Groups.Add(group);
                }

                var item = new ListViewItem(detail.ConnectionName);
                item.SubItems.Add(detail.Organization);
                item.SubItems.Add(detail.ServerName);
                item.SubItems.Add(detail.OrganizationVersion);
                item.Tag = detail;
                item.Group = group;

                if (detail.UseOnline)
                {
                    item.ImageIndex = 2;
                }
                else if (detail.UseOsdp)
                {
                    item.ImageIndex = 2;
                }
                else if (detail.UseIfd)
                {
                    item.ImageIndex = 1;
                }
                else
                {
                    item.ImageIndex = 0;
                }

                this.lvConnections.Items.Add(item);
            }

            var groups = new ListViewGroup[this.lvConnections.Groups.Count];

            this.lvConnections.Groups.CopyTo(groups, 0);

            Array.Sort(groups, new GroupComparer());

            this.lvConnections.BeginUpdate();
            this.lvConnections.Groups.Clear();
            this.lvConnections.Groups.AddRange(groups);
            this.lvConnections.EndUpdate();
        }

        /// <summary>
        /// Gets or sets the connection list.
        /// </summary>
        public CrmConnections ConnectionList { get; set; }

        /// <summary>
        /// Gets the selected connection.
        /// </summary>
        public ConnectionDetail SelectedConnection { get; private set; }

        /// <summary>
        /// Gets a value indicating whether had created new connection.
        /// </summary>
        public bool HadCreatedNewConnection
        {
            get { return this.hadCreatedNewConnection; }
        }

        /// <summary>
        /// The load images.
        /// </summary>
        private void LoadImages()
        {
            this.lvConnections.SmallImageList = new ImageList();
            this.lvConnections.SmallImageList.Images.Add(ResourceManager.GetImage("McTools.Xrm.Connection.WinForms.Resources.server.png"));
            this.lvConnections.SmallImageList.Images.Add(ResourceManager.GetImage("McTools.Xrm.Connection.WinForms.Resources.server_key.png"));
            this.lvConnections.SmallImageList.Images.Add(ResourceManager.GetImage("McTools.Xrm.Connection.WinForms.Resources.CRMOnlineLive_16.png"));
        }

        /// <summary>
        /// The button new connection click.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        private void BtnNewConnectionClick(object sender, EventArgs e)
        {
            var connectionForm = new ConnectionForm(true)
            {
                ConnectionList = this.ConnectionList, 
                StartPosition = FormStartPosition.CenterParent
            };

            if (connectionForm.ShowDialog(this) == DialogResult.OK)
            {
                this.SelectedConnection = connectionForm.CrmConnectionDetail;
                this.hadCreatedNewConnection = true;

                var item = new ListViewItem(this.SelectedConnection.ConnectionName);
                item.SubItems.Add(this.SelectedConnection.ServerName);
                item.SubItems.Add(this.SelectedConnection.Organization);
                item.Tag = this.SelectedConnection;

                this.lvConnections.Items.Add(item);
                this.lvConnections.SelectedItems.Clear();
                item.Selected = true;

                this.BValidateClick(sender, e);
            }
        }

        /// <summary>
        /// The button delete click.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        private void BtnDeleteClick(object sender, EventArgs e)
        {
            if (this.lvConnections.SelectedItems.Count > 0)
            {
                this.connectionManager.ConnectionsList.Connections.Remove((ConnectionDetail)this.lvConnections.SelectedItems[0].Tag);
                this.connectionManager.SaveConnectionsFile(this.ConnectionList);

                this.lvConnections.Items.Remove(this.lvConnections.SelectedItems[0]);
            }
        }

        /// <summary>
        /// The left connections mouse double click.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        private void LvConnectionsMouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.BValidateClick(sender, e);
        }

        /// <summary>
        /// The b validate click.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        private void BValidateClick(object sender, EventArgs e)
        {
            if (this.lvConnections.SelectedItems.Count == 1)
            {
                this.SelectedConnection = this.lvConnections.SelectedItems[0].Tag as ConnectionDetail;

                this.DialogResult = DialogResult.OK;
                this.Close();
            }
        }

        /// <summary>
        /// The b cancel click.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        private void BCancelClick(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }

        /// <summary>
        /// The lv connections column click.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        private void LvConnectionsColumnClick(object sender, ColumnClickEventArgs e)
        {
            this.lvConnections.Sorting = this.lvConnections.Sorting == SortOrder.Ascending ? SortOrder.Descending : SortOrder.Ascending;
            this.lvConnections.ListViewItemSorter = new ListViewItemComparer(e.Column, this.lvConnections.Sorting);
        }
    }
}
